package pit.com.ordermobilesystem;

import java.io.UnsupportedEncodingException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import pit.com.ordermobilesystem.BaseFragment.TypeLoadingMore;
import pit.com.ordermobilesystem.adapter.StoreAdapter;
import pit.com.ordermobilesystem.http.HttpApiException;
import pit.com.ordermobilesystem.http.OrderSystemHttpService;
import pit.com.ordermobilesystem.provider.OrderMobileProvider.CategoryTable;
import pit.com.ordermobilesystem.sharepreference.OrderSharePreference;
import pit.com.ordermobilesystem.util.Utils;

import com.aviary.android.feather.FeatherActivity;
import com.aviary.android.feather.library.Constants;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.TextureView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.graphics.Bitmap;
public class AddCategoryActivity extends BaseFragmentActivity{
	Uri mImageUri;
	DisplayImageOptions options;
	JSONObject category;
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.activity_add_category);
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.ic_no_image)
		.showImageForEmptyUri(R.drawable.ic_no_image)
		.showImageOnFail(R.drawable.ic_no_image)
		.cacheInMemory(true)
		.cacheOnDisk(true)
		.considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.build();
	        ImageView img_category=(ImageView) findViewById(R.id.img_category);
	        if(getIntent().getStringExtra("data")!=null){
	        	try {
				category=new JSONObject(getIntent().getStringExtra("data"));
				imageLoader.displayImage(category.getString(CategoryTable.LINK_IMAGE), img_category, options, null);

	        	} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        }

	        img_category.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				Intent newIntent = new Intent( AddCategoryActivity.this, CameraActivity.class );
				startActivityForResult( newIntent, 1 ); 
			}
		});

	        Button bt_add=(Button) findViewById(R.id.bt_add_category);
	        bt_add.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {

				new UploadImage(TypeLoadingMore.LOADING_FIRST).execute(Utils.getRealPathFromURI(getApplicationContext(), mImageUri));
			}
		});
		getActionBar().setDisplayHomeAsUpEnabled(true);

	    
	    }
	    
	    
		@Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) 
		{
				    if(resultCode==RESULT_OK){
				                // output image path
				                mImageUri = data.getData();
				                Bundle extra = data.getExtras();
				                if( null != extra ) {
				                	ImageView img_category=(ImageView) findViewById(R.id.img_category);
				                	img_category.setImageURI(mImageUri);
                
				                 }
				    }  
		}
		
		class UploadImage extends AsyncTask<String, Void, Void> {

			TypeLoadingMore typeLoading;
			Exception exception;
			int response_code=0;
			JSONArray arrayStore;
			String url_image="";
			String name_category;
			public UploadImage(TypeLoadingMore typeLoading) {
				super();
				this.typeLoading = typeLoading;
			}
			protected void onPreExecute() {
				EditText ed_name=(EditText) findViewById(R.id.ed_category);
				name_category=ed_name.getText().toString();
				if(typeLoading==TypeLoadingMore.LOADING_FIRST){
					showProgressDialog(new DialogInterface.OnCancelListener() {
						
						@Override
						public void onCancel(DialogInterface dialog) {
							UploadImage.this.cancel(true);
							dialog.dismiss();
						}


					});
				}

			}

			protected Void doInBackground(final String... args) {
				OrderSystemHttpService httpService=new OrderSystemHttpService(OrderSharePreference.getHost(getApplicationContext()),OrderSharePreference.getPort(getApplicationContext()));
				try {
					String[] path_file={args[0]};
					JSONObject json_user=new JSONObject(OrderSharePreference.getUser(getApplicationContext()));
					JSONObject result=httpService.uploadFile(OrderSystemHttpService.URL_UPLOAD_IMAGE,json_user.getString("username"),path_file);
					if(result.getString("status").equals("ok")){		
						url_image=result.getJSONObject("data").getString("file");
						if(category==null) category=new JSONObject();
						category.put(CategoryTable.NAME_CATEGORY, name_category);
						category.put(CategoryTable.LINK_IMAGE, url_image);
						if(category.has(CategoryTable.ID_CATEGORY)){
							JSONObject data=Utils.createDataForUpdateGeneralService(category,  "os_category", CategoryTable.ID_CATEGORY);
							result=httpService.requestToService(OrderSystemHttpService.URL_UPDATE_GENERAL, data.toString());							
						}else{
							JSONObject data=Utils.createDataForInsertGeneralService(category, "os_category");
							result=httpService.requestToService(OrderSystemHttpService.URL_INSERT_GENERAL, data.toString());
						}
						if(result.getString("status").equals("ok")){
							response_code=1;
						}
					}else{
						exception=new Exception(result.getString("error"));
					}

				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					exception=e;
				} catch (HttpApiException e) {
					// TODO Auto-generated catch block
					exception=e;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					exception=e;
				}
				return null;
			}

			protected void onPostExecute(final Void unused) {

					hideProgressDialog();

				
				if(exception!=null){
					showAlert("",exception.getMessage());
				}else{
					if(response_code==1){
						setResult(RESULT_OK);
						finish();
					}else{
						finish();
					}
				}
				
			}

		}
		
		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
		    switch (item.getItemId()) {
		    // Respond to the action bar's Up/Home button
		    case android.R.id.home:
		        //NavUtils.navigateUpFromSameTask(this);
			    finish();
		        return true;
		    }
		    return super.onOptionsItemSelected(item);
		}		
		
}
